import cookie from '@/store/cookie'
import baseUrl from '@/config/website.js'
import { Clear } from "@/common/Func.js"

// 多个loading合并为一个
// let baseUrl = process.env.NODE_ENV === "development" ? "http://47.111.140.195:9000" : ""



let needLoadingRequestCount = 0
export function showLoading() {
	if (needLoadingRequestCount === 0) {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
	}
	needLoadingRequestCount++
}
export function hideLoading() {
	if (needLoadingRequestCount <= 0) return
	needLoadingRequestCount--
	if (needLoadingRequestCount === 0) {
		uni.hideLoading()
	}
}

/**
 * request function
 * @param url      请求url
 * @param data 参数
 */
const request = (conf : { url : string, data ?: any }, isToken = true, isShowLoding = true) => {
	if (isShowLoding) {
		showLoading();
	}// 获取token

	const header = {}
	if (cookie.getToken() && isToken) {
		header['X-Token'] = cookie.getToken();
	} else {

	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl.baseUrl}${conf.url}`,
			data: conf.data,
			// @ts-ignore
			method: 'POST',
			header: header,
			success: (response) => {
				// console.log(response)
				hideLoading();
				if (response.statusCode >= 200) {
					// @ts-ignore
					const { code, msg } = response.data
					if (code >= 400) {
						uni.showToast({
							title: msg,
							icon: 'none'
						})
					}
					if (code === 401) {
						console.log('授权消失---------------------------------------------------------------------------------------------------------------------------->')
						uni.navigateTo({
							url: '/pages/login/index',
							animationType: 'none'
						})
						const tenantId = uni.getStorageSync('tenantId')
						// cookie.clearAll()
						Clear()
						
						uni.setStorageSync('tenantId',tenantId)
					}
					resolve(response)
				} else {
					reject(response)
				}
			},
			fail: (err) => {
				console.log(err)
				hideLoading();
				uni.showToast({
					icon: 'none',
					title: err.errMsg,
					duration: 2000
				});
				reject(err)
			}
		})
	})
}
export default request